#include "../include/structure.h"

int sendFile(int net_fd){

    char *file_name = "1.txt";

    // 打开文件
    int file_fd = open(file_name, O_RDWR);  
    struct stat st;
    memset(&st, 0, sizeof st);
    fstat(file_fd, &st);

    send(net_fd, &st.st_size, sizeof(off_t), MSG_NOSIGNAL);

    // 写给客户端文件名字
    int name_len = strlen(file_name);
    // 先传文件名大小再传文件名
    // 别bb信号，免得我崩溃了😩
    send(net_fd, &name_len, sizeof(int), MSG_NOSIGNAL);
    send(net_fd, file_name, name_len, MSG_NOSIGNAL);

    
    // 循环读取文件内容, 循环发送
    while(1){
        // 读取文件内容
        char buf[1024] = {0};
        ssize_t file_len = read(file_fd, buf, sizeof(buf));
        if(file_len == 0){
            printf("文件读完 \n");
            break;
        }

        int ret1 = send(net_fd, &file_len, sizeof(ssize_t), MSG_NOSIGNAL);
        if(ret1 == -1){
            printf("对面亖了\n");
            break;
        }
        // 文件内容: 发送给客户端
        int ret2 = send(net_fd, buf, file_len, MSG_NOSIGNAL);
        if(ret2 == -1){
            printf("对面亖了\n");
            break;
        }
        printf("file_len: %ld \n", file_len);

        //sleep(1);
    }
    
    close(file_fd);
    return 0;
}